package com.jianpengfei.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

public class IOUtil {

	private IOUtil() {};
	
	
	/**
	 * 流对象数据(多个)  关闭流
	 * @param closeables
	 */
	public static void closeStream(Closeable ... closeables) {
		try {
			for (Closeable temp : closeables) {
				temp.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 读取文本文件  使用缓冲流
	 * @param file
	 * @return
	 * @throws Exception
	 */
	public static String readTextFile(File file) throws Exception {
		
		StringBuffer buffer = new StringBuffer();
		
		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
		
		Scanner scanner = new Scanner(bis);
		
		while(scanner.hasNextLine()) {
			buffer.append(scanner.nextLine());
		}
		
		return buffer.toString();
	}
	
	public static void copyTo(InputStream input,
			OutputStream output,
			boolean needClosInput,
			boolean needClosOutput) throws Exception {
		
		if (input != null || output != null) {
			return ;
		}
		
		BufferedInputStream bis = new BufferedInputStream(input);
		BufferedOutputStream bos = new BufferedOutputStream(output);
		
		byte[] buffer = new byte[1024];
		
		while(bis.read(buffer) != -1) {
			bos.write(buffer);
		}
		
		bos.flush();
		
		if(needClosInput) {
			closeStream(input);
		}
		
		if (needClosOutput) {
			closeStream(output);
		}
	}
	
}
